package game.metalmax.module.server
{
	import flash.geom.Point;
	import flash.utils.ByteArray;
	
	import game.metalmax.DataLocator;
	import game.metalmax.controller.Notifications;
	import game.metalmax.entity.character.Character;
	import game.metalmax.entity.character.Hero;
	import game.metalmax.entity.character.Vehicle;
	import game.metalmax.entity.server.ServerConfig;
	import game.metalmax.factory.PacketFactory;
	import game.metalmax.module.character.CharacterManager;
	import game.metalmax.module.world.WorldManager;
	import game.metalmax.packet.IPacket;
	import game.metalmax.packet.character.PHero;
	import game.metalmax.packet.server.EnterGameRequest;
	import game.metalmax.packet.server.EnterGameResponse;
	import game.metalmax.packet.server.ExitGameRequest;
	import game.metalmax.packet.server.LoginRequest;
	import game.metalmax.packet.server.LoginResponse;
	
	import showtime.framework.engine.map.MapObjectType;
	import showtime.framework.events.SocketEvent;
	import showtime.framework.manager.DataBaseManager;
	import showtime.framework.mvc.patterns.proxy.Proxy;
	import showtime.framework.net.tcp.BaseSocket;

	/**
	 * NetProxy.as
	 * Yin Hao
	 * @version 1.0.0
	 * 
	 * Description.
	 * 
	 * Copyright (c) 2012 Yin Hao
	 * 
	 * Permission is hereby granted, free of charge, to any person obtaining a copy
	 * of this software and associated documentation files (the "Software"), to deal
	 * in the Software without restriction, including without limitation the rights
	 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	 * copies of the Software, and to permit persons to whom the Software is
	 * furnished to do so, subject to the following conditions:
	 * 
	 * The above copyright notice and this permission notice shall be included in
	 * all copies or substantial portions of the Software.
	 * 
	 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	 * THE SOFTWARE.
	 */
	public class ServerProxy extends Proxy
	{
		static private var socket:BaseSocket = null;
		static private var buffer:ByteArray = null;

		public function ServerProxy()
		{
			super(String(ServerProxy));
		}
		
		override public function onRegister():void
		{
			super.onRegister();

			GateWay.register(Header.LOGIN_GAME_S2C, loginS2C);
			GateWay.register(Header.ENTER_GAME_S2C, enterGameS2C);
			
			buffer = new ByteArray();			
			var serverConfig:ServerConfig =  DataBaseManager.getInstance().read(ServerConfig, "GAME_SERVER");
			socket = new BaseSocket().connect(serverConfig.ip, serverConfig.port);
			socket.callback = serverCallback;
			
			socket.addEventListener(SocketEvent.CONNECT, onConnect);
			socket.addEventListener(SocketEvent.CLOSE, onClose);
			socket.addEventListener(SocketEvent.IO_ERROR, onIoError);
		}
		
		private function onConnect(event:SocketEvent):void
		{
			loginC2S("showtime1985@gmail.com", "123456")
			//sendNotification(Notifications.LOIN_GAME);
		}
		
		private function onClose(event:SocketEvent):void
		{
			
		}
		
		private function onIoError(event:SocketEvent):void
		{
			sendNotification(Notifications.OPEN_ALERT_WINDOW, "服务器未开启，请稍后再试！");
		}
		
		private function serverCallback(inStream:ByteArray):void
		{
			var header:int = inStream.readInt();
			
			var packet:Object = PacketFactory.getPacket(header);
			
			packet.read(inStream);
			
			GateWay.dispatch(header, packet);
		}
		
		static public function sendPacketToServer(header:int, packet:IPacket):void
		{
			buffer.clear();
			buffer.writeInt(header);
			packet.write(buffer);

			socket.sendPacket(buffer);
		}

		public function loginC2S(email:String, secret:String):void
		{
			var request:LoginRequest = new LoginRequest();
			request.email = email;
			request.secret = secret;			
			
			ServerProxy.sendPacketToServer(Header.LOGIN_GAME_C2S, request);
		}
		
		private function loginS2C(packet:LoginResponse):void
		{
			switch (packet.result)
			{
				case 1:
				{
					DataLocator.getInstance().email = packet.email;
					enterGameC2S();
					break;
				}
				case 2:
				{		
					sendNotification(Notifications.OPEN_ALERT_WINDOW, "登录失败");
					break;
				}
				default:
				{
					
				}
			}
		}
		
		public function enterGameC2S():void
		{
			var request:EnterGameRequest = new EnterGameRequest();
			request.email = DataLocator.getInstance().email;
			ServerProxy.sendPacketToServer(Header.ENTER_GAME_C2S, request);
		}
		
		private function enterGameS2C(packet:EnterGameResponse):void
		{
			WorldManager.getInstance().nowMapID = packet.mapID;
			
			var hero:Hero = null;
			for each (var pHero:PHero in packet.heros)
			{			
				hero = new Hero();
				hero.id = pHero.id;
				hero.name = pHero.name;
				hero.type = pHero.type;
				hero.spawnPoint = new Point(pHero.position.x, pHero.position.y);
				hero.direction = pHero.avatar.direction;
				hero.animationName = pHero.avatar.animationName;
				hero.graphicID = pHero.avatar.graphicID;
				hero.animationConfigID = pHero.avatar.animationConfigID;
				
				if (pHero.vehicle != null)
				{
					hero.vehicle = new Vehicle();
					hero.vehicle.id = pHero.vehicle.id;
					hero.vehicle.type = MapObjectType.VEHICLE;
					hero.vehicle.direction = pHero.vehicle.avatar.direction;
					hero.vehicle.animationName = pHero.vehicle.avatar.animationName;
					hero.vehicle.graphicID = pHero.vehicle.avatar.graphicID;
					hero.vehicle.animationConfigID = pHero.vehicle.avatar.animationConfigID;
				}
				
				if (hero.type == Character.TYPE_LEADING)
				{
					CharacterManager.getInstance().self = hero;
				}
				else
				{
					CharacterManager.getInstance().heros.push(hero);
				}
			}
			
			sendNotification(Notifications.ENTER_SCENE);
		}
		
		public function exitGameC2S():void
		{
			var request:ExitGameRequest = new ExitGameRequest();
			request.email = DataLocator.getInstance().email;
			
			ServerProxy.sendPacketToServer(Header.EXIT_GAME_C2S, request);
		}
	}
}